<template>
  <Modal
    :mask-closable="false"
    v-model="addModal"
    :title="edit ? '上传素材' : '编辑'"
    :footer-hide="true"
    :draggable="true"
    :width="1000"
    @on-visible-change="
      (e) => {
        !e && haddleCancel();
      }
    "
  >
    <Form ref="create" :model="toolInfo" :rules="rules" :label-width="70">
      <Row>
        <Col :span="11">
          <FormItem label="名称" prop="name" required>
            <Input
              v-model="toolInfo.name"
              placeholder="请输入名称"
              :maxlength="20"
            />
          </FormItem>
          <FormItem label="项目" prop="project_id" required>
            <Select
              v-model="toolInfo.project_id"
              placeholder="请选择项目"
              :filterable="projectAddList.length >= 10"
              @on-open-change="showAll"
              clearable
            >
              <Option
                v-for="item in projectAddList"
                :value="+item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="标签" prop="tagIds">
            <Select
              placeholder="请选择标签"
              multiple
              filterable
              allow-create
              @on-open-change="openChange"
              @on-change="tagChange"
              ref="tags"
              v-model="toolInfo.tagIds"
            >
              <Option
                v-for="item in tagAddList"
                :value="isNaN(item.value) ? item.value : parseInt(item.value)"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="简介说明" prop="desc">
            <Input
              type="textarea"
              :rows="4"
              v-model="toolInfo.desc"
              placeholder="简单明了直击主题"
              :maxlength="50"
            />
          </FormItem>
          <FormItem label="图片" prop="imgfiles">
            <Upload
              :action="fileUrl"
              :accept="imageType"
              multiple
              :show-upload-list="false"
              :before-upload="imgBeforeUpload"
              :on-error="imgUploadError"
            >
              <Button
                type="primary"
                :loading="loadingImgUpload"
                @click="showMaxSize = true"
                >上传</Button
              >
              <Tooltip
                :max-width="300"
                placement="top"
                :content="'支持图片格式：' + imageType"
                class="ivu-ml-8"
              >
                <Icon type="ios-alert-outline" size="20" color="#2db7f5" />
              </Tooltip>
            </Upload>
            <div class="imgList1 ivu-mt-16">
              <div
                class="demo-upload-list"
                v-for="(item, index) in toolInfo.imgfiles"
                :key="item.thumb_url"
              >
                <img :src="item.thumb_url" fit="cover" width="40" height="40" />
                <div class="demo-upload-list-cover">
                  <Icon
                    type="ios-eye-outline"
                    @click="handleView(index)"
                  ></Icon>
                  <Icon
                    type="ios-trash-outline"
                    @click="handleImgRemove(item)"
                  ></Icon>
                </div>
              </div>
              <template v-for="(item, index) in imgLoadings" :key="index">
                <div
                  class="demo-upload-list"
                  style="position: relative"
                  v-if="item"
                >
                  <Spin fix style="line-height: 12px"
                    ><Icon
                      type="ios-loading"
                      size="18"
                      class="demo-spin-icon-load"
                    ></Icon>
                    <div>loding</div></Spin
                  >
                </div>
              </template>
            </div>
          </FormItem>
          <FormItem label="视频" prop="vedioFiles">
            <Upload
              :action="fileUrl"
              :accept="vedioType"
              multiple
              :show-upload-list="false"
              :before-upload="videoBeforeUpload"
              :on-error="videoUploadError"
            >
              <Button
                type="primary"
                :loading="loadingVideoUpload"
                @click="showMaxVideoSize = true"
                >上传</Button
              >
              <Tooltip
                :max-width="300"
                placement="top"
                :content="'支持视频格式：' + vedioType"
                class="ivu-ml-8"
              >
                <Icon type="ios-alert-outline" size="20" color="#2db7f5" />
              </Tooltip>
            </Upload>
            <div class="imgList1 ivu-mt-16">
              <div
                class="demo-upload-list"
                v-for="item in toolInfo.vedioFiles"
                :key="item.thumb_url"
              >
                <img :src="item.thumb_url" fit="cover" width="40" height="40" />
                <div class="demo-upload-list-cover">
                  <Icon
                    type="ios-eye-outline"
                    @click="handleVideoView(item)"
                  ></Icon>
                  <Icon
                    type="ios-trash-outline"
                    @click="handleVideoRemove(item)"
                  ></Icon>
                </div>
              </div>
              <template v-for="(item, index) in videoLoadings" :key="index">
                <div
                  class="demo-upload-list"
                  style="position: relative"
                  v-if="item"
                >
                  <Spin fix style="line-height: 12px"
                    ><Icon
                      type="ios-loading"
                      size="18"
                      class="demo-spin-icon-load"
                    ></Icon>
                    <div>loding</div></Spin
                  >
                </div>
              </template>
            </div>
          </FormItem>
          <FormItem label="附件" prop="file">
            <Upload
              :action="fileUrl"
              :accept="docType"
              :show-upload-list="false"
              :before-upload="handleBeforeUpload"
              :on-error="handleUploadError"
            >
              <Button type="primary" :loading="loadingUpload">上传</Button>
              <Tooltip
                :max-width="300"
                placement="top"
                :content="'支持文件格式：' + docType"
                class="ivu-ml-8"
              >
                <Icon type="ios-alert-outline" size="20" color="#2db7f5" />
              </Tooltip>
            </Upload>
            <Progress
              v-if="progress && progress != 100"
              :percent="progress"
              :stroke-width="5"
            />
            <ul class="ivu-upload-list">
              <li
                class="ivu-upload-list-file ivu-upload-list-file-finish"
                style="display: inline-block"
                v-for="item in files"
                :key="item.url"
              >
                <span
                  ><Icon type="ios-document-outline" /> {{ item.name }}</span
                >
                <i
                  class="ivu-icon ivu-icon-ios-close ivu-upload-list-remove"
                  style=""
                  @click="handleRemove()"
                ></i>
              </li>
            </ul>
          </FormItem>
        </Col>
        <Col :span="1" class="ivu-text-center">
          <Divider type="vertical" style="height: 100%" />
        </Col>
        <Col :span="12">
          <FormItem label="年龄" prop="age_id">
            <Select
              v-model="toolInfo.age_id"
              placeholder="请选择年龄"
              clearable
            >
              <Option
                v-for="item in ageAddList"
                :value="+item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="分类" prop="category_ids">
            <Tabs type="card">
              <TabPane
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
              >
                <CheckboxGroup v-model="toolInfo.category_ids">
                  <Checkbox
                    v-for="el in item.children"
                    :key="el.value"
                    :label="el.value"
                    >{{ el.label }}</Checkbox
                  >
                </CheckboxGroup>
              </TabPane>
            </Tabs>
          </FormItem>
        </Col>
      </Row>
    </Form>
    <div slot="footer" style="text-align: right">
      <Button type="default" @click="haddleCancel">取消</Button>
      <Button
        type="primary"
        @click="ok"
        style="margin-left: 10px"
        :loading="btnLoading"
        >确定</Button
      >
    </div>
    <Spin size="large" fix v-if="spinShow"></Spin>
  </Modal>
</template>
<script>
import {
  createTool,
  uploadImg,
  uploadVideo,
  uploadFile,
  toolEditInfo,
  checkTgaStatus,
  updateTool,
} from "@api/toolnavigation.js";
export default {
  props: ["edit"],
  data() {
    return {
      showMaxVideoSize: false,
      showMaxSize: false,
      spinShow: false,
      addModal: false,
      btnLoading: false,
      loadingImgUpload: false,
      loadingVideoUpload: false,
      loadingUpload: false,
      fileUrl: "",
      projectAddList: [],
      tagAddList: [],
      ageAddList: [],
      initTagList: [],
      typeList: [],
      imageType: "",
      vedioType: "",
      docType: "",
      toolInfo: {
        id: "",
        name: "",
        project_id: "",
        desc: "",
        tag_ids: [],
        tagIds: [],
        file: "",
        imgfiles: [],
        vedioFiles: [],
        age_id: "",
        category_ids: [],
      },
      tags: [],
      rules: {
        name: [{ required: true, message: "请输入名称" }],
        project_id: [{ required: true, message: "请选择项目" }],
      },
      progress: 0,
      progress1: 0,
      controller: null,
      controller1: null,
      controller2: null,
      files: [],
      filesNum: [],
      filesVideoNum: [],
      maxFiles: 10,
      maxVideo: 5,
      imgLoadings: [],
      videoLoadings: [],
    };
  },
  watch: {
    tags(newData, oldData) {
      if (newData.length > oldData.length) {
        let flag = false;
        let hasTags = false;
        this.tagAddList.forEach((item) => {
          if (
            newData[newData.length - 1] == item.value ||
            newData[newData.length - 1] == item.label
          ) {
            flag = true;
            this.toolInfo.tagIds[this.toolInfo.tagIds.length - 1] = isNaN(
              item.value
            )
              ? item.value
              : parseInt(item.value);
            this.toolInfo.tagIds = [...new Set(this.toolInfo.tagIds)];
            return;
          }
        });
        if (!flag) {
          checkTgaStatus({ name: newData[newData.length - 1], type: 2 }).then(
            (res) => {
              if (res.res) {
                this.tagAddList.push({
                  value: isNaN(newData[newData.length - 1])
                    ? newData[newData.length - 1]
                    : parseInt(newData[newData.length - 1]),
                  label: newData[newData.length - 1],
                });
                this.toolInfo.tagIds[this.toolInfo.tagIds.length - 1] = isNaN(
                  newData[newData.length - 1]
                )
                  ? newData[newData.length - 1]
                  : parseInt(newData[newData.length - 1]);
                hasTags = true;
                return;
              }
              if (!hasTags) {
                let tagIds = JSON.parse(JSON.stringify(this.toolInfo.tagIds));
                tagIds.pop();
                this.toolInfo.tagIds = tagIds;
                this.$Message.success("此标签已被禁用！");
              }
            }
          );
        }
      }
    },
  },
  methods: {
    openChange(e) {
      if (!e) {
        this.$refs.tags.query = "";
      }
    },
    tagChange(e) {
      this.tags = this.toolInfo.tagIds;
    },
    showAll(e) {
      if (e) {
        let downList = document.querySelectorAll(
          ".ivu-select-dropdown-list .ivu-select-item"
        );
        downList.forEach((item) => {
          item.style.display = "block";
        });
      }
    },
    haddleCancel() {
      if (this.controller) {
        this.controller.abort();
        this.progress = 0;
      }
      if (this.controller1) {
        this.controller1.abort();
      }
      if (this.controller2) {
        this.controller2.abort();
      }
      this.btnLoading = false;
      this.loadingImgUpload = false;
      this.loadingVideoUpload = false;
      this.loadingUpload = false;
      this.addModal = false;
    },
    changeData(data) {
      let list = [];
      data.forEach((item) => {
        if (item.children && item.children.length > 0) {
          list.push(item);
        }
      });
      return list;
    },
    initData() {
      this.toolInfo = {
        id: "",
        name: "",
        project_id: "",
        desc: "",
        tag_ids: [],
        tagIds: [],
        file: "",
        imgfiles: [],
        vedioFiles: [],
        age_id: "",
        category_ids: [],
      };
      this.filesNum = [];
      this.filesVideoNum = [];
      this.files = [];
      this.imgLoadings = [];
      this.videoLoadings = [];
      this.loadingImgUpload = false;
      this.loadingUpload = false;
      this.loadingVideoUpload = false;
    },
    init(id = 0) {
      this.addModal = true;
      this.spinShow = true;
      this.initData();
      toolEditInfo({ id: id })
        .then((res) => {
          this.projectAddList = res.condition.project;
          this.tagAddList = res.condition.tag;
          this.initTagList = [...res.condition.tag];
          this.typeList = this.changeData(res.condition.category);
          this.ageAddList = res.condition.age;
          this.imageType = res.support_image_type.join(" , ");
          this.vedioType = res.support_video_type.join(" , ");
          this.docType = res.support_type.join(" , ");
          this.spinShow = false;
          if (id > 0) {
            this.toolInfo = {
              id: res.id,
              name: res.name,
              project_id: res.project_id,
              desc: res.desc,
              tagIds: res.tag_ids,
              file: res.file,
              age_id: res.age_id,
              imgfiles: [],
              vedioFiles: [],
              category_ids: res.category_ids,
            };
            res.image.forEach((item) => {
              this.filesNum.push({
                name: item.file,
                url: item.file_url,
              });
              this.toolInfo.imgfiles.push({
                file: item.file,
                url: item.file_url,
                thumb_url: item.thumb_url,
              });
            });
            res.video.forEach((item) => {
              this.filesVideoNum.push({
                name: item.file,
                url: item.file_url,
              });
              this.toolInfo.vedioFiles.push({
                file: item.file,
                url: item.file_url,
                thumb_url: item.thumb_url,
              });
            });
            this.files = res.file_name ? [{ name: res.file_name }] : [];
          }
        })
        .catch(() => {
          this.spinShow = false;
        });
    },
    ok() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          this.addTool();
        } else {
          this.addModal = true;
          return;
        }
      });
    },
    addTool() {
      if (
        this.loadingUpload ||
        this.loadingVideoUpload ||
        this.loadingImgUpload
      ) {
        this.$Message.success("文件还在上传中请等待一会~");
        return;
      }
      this.btnLoading = true;
      let tagarr = [];
      this.toolInfo.tagIds.forEach((item) => {
        let hasTag = false;
        this.initTagList.forEach((el) => {
          if (item == el.value) {
            tagarr.push(el);
            hasTag = true;
            return;
          }
        });
        if (!hasTag) {
          tagarr.push({ value: 0, label: item });
        }
      });
      let preview_image = [];
      this.toolInfo.imgfiles.forEach((item) => {
        preview_image.push(item.file);
      });
      let videos = [];
      this.toolInfo.vedioFiles.forEach((item) => {
        videos.push(item.file);
      });
      const params = {
        name: this.toolInfo.name,
        project_id: this.toolInfo.project_id,
        desc: this.toolInfo.desc,
        tags: tagarr,
        file: this.toolInfo.file,
        video: videos,
        image: preview_image,
        age_id: this.toolInfo.age_id,
        category_ids: this.toolInfo.category_ids,
      };
      if (this.edit) {
        createTool(params)
          .then((res) => {
            this.$Message.success("添加成功");
            this.addModal = false;
            this.btnLoading = false;
            this.$emit("refresh", true);
          })
          .catch(() => {
            this.btnLoading = false;
          });
      } else {
        updateTool(Object.assign({}, params, { id: this.toolInfo.id }))
          .then((res) => {
            this.$emit("refresh");
            this.$Message.success("编辑成功");
            this.addModal = false;
            this.btnLoading = false;
          })
          .catch(() => {
            this.btnLoading = false;
          });
      }
    },
    imgBeforeUpload(e) {
      if (this.filesNum.length >= this.maxFiles) {
        if (this.showMaxSize) {
          this.$Message.success("图片数量不能超过" + this.maxFiles + "张！");
          this.showMaxSize = false;
        }
        return false;
      }
      if (e.size > 1024 * 1024 * 20) {
        this.$Message.error("文件大小不能超过20M");
        return false;
      }
      this.imgLoadings.push(true);
      let index = this.imgLoadings.length - 1;
      this.filesNum.push(e);
      this.loadingImgUpload = true;
      this.controller1 = new AbortController();
      uploadImg(
        { site: "tool", module: "preview_image", file: e, min: "500,500" },
        this
      )
        .then((res) => {
          this.toolInfo.imgfiles.push(res);
          this.imgLoadings[index] = false;
          let flag = false;
          this.imgLoadings.forEach((item) => {
            if (item) {
              flag = true;
            }
          });
          this.loadingImgUpload = flag;
          if (!this.loadingImgUpload) {
            this.imgLoadings = [];
          }
        })
        .catch((res) => {
          this.imgLoadings[index] = false;
          let flag = false;
          this.imgLoadings.forEach((item) => {
            if (item) {
              flag = true;
            }
          });
          this.loadingImgUpload = flag;
          if (!this.loadingImgUpload) {
            this.imgLoadings = [];
          }
        });

      return false;
    },
    imgUploadError(error) {
      this.$Message.error(error);
      this.loadingImgUpload = false;
    },
    handleImgRemove(file) {
      const fileList = this.toolInfo.imgfiles;
      this.toolInfo.imgfiles.splice(
        fileList.findIndex((item) => {
          return item.file == file.file;
        }),
        1
      );
      this.filesNum.splice(
        fileList.findIndex((item) => {
          return item.file == file.file;
        }),
        1
      );
    },
    handleView(index) {
      let imgArr = [];
      this.toolInfo.imgfiles.forEach((item) => {
        imgArr.push(item.url);
      });
      this.$hevueImgPreview({
        multiple: true,
        nowImgIndex: index,
        imgList: imgArr,
      });
    },
    videoBeforeUpload(e) {
      if (this.filesVideoNum.length >= this.maxVideo) {
        if (this.showMaxVideoSize) {
          this.$Message.success("视频数量不能超过" + this.maxVideo + "个！");
          this.showMaxVideoSize = false;
        }
        return false;
      }
      if (e.size > 1024 * 1024 * 500) {
        this.$Message.error("文件大小不能超过500M");
        return false;
      }
      this.loadingVideoUpload = true;
      this.videoLoadings.push(true);
      let index = this.videoLoadings.length - 1;
      this.filesVideoNum.push(e);
      this.controller2 = new AbortController();
      uploadVideo({ site: "tool", module: "video", file: e }, this)
        .then((res) => {
          this.toolInfo.vedioFiles.push(res);
          this.videoLoadings[index] = false;
          let flag = false;
          this.videoLoadings.forEach((item) => {
            if (item) {
              flag = true;
            }
          });
          this.loadingVideoUpload = flag;
          if (!this.loadingVideoUpload) {
            this.videoLoadings = [];
          }
        })
        .catch((res) => {
          this.videoLoadings[index] = false;
          let flag = false;
          this.videoLoadings.forEach((item) => {
            if (item) {
              flag = true;
            }
          });
          this.loadingVideoUpload = flag;
          if (!this.loadingVideoUpload) {
            this.videoLoadings = [];
          }
        });

      return false;
    },
    videoUploadError(error) {
      this.$Message.error(error);
      this.loadingVideoUpload = false;
    },
    handleVideoRemove(file) {
      const fileList = this.toolInfo.vedioFiles;
      this.toolInfo.vedioFiles.splice(
        fileList.findIndex((item) => {
          return item.file == file.file;
        }),
        1
      );
      this.filesVideoNum.splice(
        fileList.findIndex((item) => {
          return item.file == file.file;
        }),
        1
      );
    },
    handleVideoView(item) {
      this.$Modal.info({
        width: 500,
        okText: "关闭",
        content: `<video src="${item.url}" controls disablePictureInPicture="true"
          controlslist="nodownload nofullscreen" style="width:100%;max-height:600px"></video>`,
      });
    },
    handleBeforeUpload(e) {
      if (e.size > 2 * 1024 * 1024 * 1024) {
        this.$Message.error("文件大小不能超过2G");
        return false;
      }
      this.loadingUpload = true;
      this.controller = new AbortController();
      this.progress = 0;
      this.files = [];
      this.toolInfo.file = null;
      uploadFile({ site: "tool", module: "nav", file: e }, this)
        .then((res) => {
          this.toolInfo.file = res.file;
          this.files = [e];
          this.loadingUpload = false;
        })
        .catch((res) => {
          this.loadingUpload = false;
        });
      return false;
    },
    handleUploadError(error) {
      this.$Message.error(error);
      this.loadingUpload = false;
    },
    handleRemove() {
      this.files = [];
      this.toolInfo.file = "";
    },
  },
};
</script>
<style lang="less" scoped>
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.imgList {
  width: 100%;
  white-space: nowrap;
  overflow: auto;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
<style>
.ivu-modal-confirm-body {
  padding-left: 0 !important;
}
.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
